package com.lzx.adx.report.controller.v1.aqy;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.AqyYdEnum;
import com.lzx.adx.report.model.aqy.AqyRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.biz.product.YouDaoChannelHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RequestMapping("/aqy/yd")
@RestController
@Slf4j
public class AqyYdController {


    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;


    @GetMapping("/report")
    public ResponseEntity report(AqyRequest aqyRequest, HttpServletRequest request) {
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(aqyRequest.getDspId());
        log.info("账号为{},收到{}点击数据的请求参数为{}", accountDTO.getId(), accountDTO.getName(), JsonUtils.toJsonString(aqyRequest));
        ReportDTO reportDTO = reportMapper.toReportDTO(aqyRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(aqyRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportDTO.setImeiSum(aqyRequest.getImei());
        reportDTO.setImei("");
        reportDTO.setOaidSum(aqyRequest.getOaidSum());
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });
        String finalUrl = YouDaoChannelHelper.covertAqyYdUrl(accountDTO, reportDTO);
        log.info("账号为{},完整的{}请求地址为{}", aqyRequest.getDspId(), accountDTO.getName(), finalUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{},完整的{}请求响应的结果为{}", aqyRequest.getDspId(), accountDTO.getName(), body);

        return ResponseEntity.ok(new Result());

    }

    /**
     *
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/wb/callback")
    public ResponseEntity callBackUrl(String requestId, String conv_action) throws Exception {
        log.info("58同城回调爱奇艺信息，请求流水号{},回调类型为{}", requestId, conv_action);
        if (StringUtils.isBlank(requestId)) {
            log.info("58同城回调爱奇艺信息，请求流水号空");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //目前只有安卓 其实就用安卓即可
        String aqyCode = AqyYdEnum.getAqyCode(conv_action);
        if (null == aqyCode) {
            log.info("58同城回调爱奇艺信息当前流水号：{}，事件类型不合法，不做数据回传", requestId);
            return ResponseEntity.ok(new Result());
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        long currentTimeMillis = System.currentTimeMillis();
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
            reportDTO.setResultType(conv_action);
            reportDTO.setResultTime(String.valueOf(currentTimeMillis));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,conv_action);
        } else {
            log.error("当前流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String callback = reportDTO.getCallback();
        String decodeUrl = URLUtil.decode(callback, StandardCharsets.UTF_8);
        //4.拼装最好的完整链接
        String finalResultUrl = decodeUrl + "&event_type=" + aqyCode;
        log.info("账号为{},请求流水号为{}58同城回调爱奇艺接口地址{}", accountDTO.getId(), requestId, finalResultUrl);
        HttpRequest body = HttpUtil.createGet(finalResultUrl);
        String result = body.execute().body();
        log.info("账号为{},请求流水号为{}58同城回调爱奇艺接口响应的结果为{}", accountDTO.getId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }







    /**
     * 饿了么回传
     *
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("/xy/callback")
    public ResponseEntity xyCallBackUrl(String requestId, String conv_action) throws Exception {
        log.info("星野回调爱奇艺信息，请求流水号{},回调类型为{}", requestId, conv_action);
        if (StringUtils.isBlank(requestId) || StringUtils.isBlank(conv_action)) {
            log.info("星野回调爱奇艺信息异常");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        //1.把转换结果更新到数据库
        Map<String, Object> params = new HashMap<>();
        params.put("bizRequestId", requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if (CollectionUtil.isNotEmpty(list)) {
            reportDTO = list.get(0);
        } else {
            log.error("当前流水号{}，系统当前不存在", requestId);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String aqyCode = jsonObject.getString(conv_action);
        if (StringUtils.isBlank(aqyCode)) {
            log.info("星野回调爱奇艺当前流水号：{}，事件类型{}不合法，不做数据回传", requestId, conv_action);
            return ResponseEntity.ok(new Result());
        }
        reportDTO.setResultType(conv_action);
        reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
        reportDTO.setUpdateTime(new Date());
        reportService.updateData(reportDTO,conv_action);
        //2.从缓存加载配置
        String callback = reportDTO.getCallback();
        String decodeUrl = URLUtil.decode(callback, StandardCharsets.UTF_8);
        //4.拼装最好的完整链接
        String finalResultUrl = decodeUrl + "&event_type=" + aqyCode;
        log.info("账号为{},请求流水号为{}星野回调爱奇艺接口地址{}", accountDTO.getId(), requestId, finalResultUrl);
        HttpRequest body = HttpUtil.createGet(finalResultUrl);
        String result = body.execute().body();
        log.info("账号为{},请求流水号为{}星野回调爱奇艺接口响应的结果为{}", accountDTO.getId(), requestId, result);
        return ResponseEntity.ok(new Result());
    }


}
